new Vue({
    el: '#app',
    data: {
        userInfo: {
            userName: '',
            roleId: ''
        },
        stats: {
            current: 0,
            todayIn: 0,
            todayOut: 0,
            todayIncome: 0
        },
        parkingRecords: [],
        availableSpots: [],
        searchKey: '',
        showEntryModal: false,
        showExitModal: false,
        entryForm: {
            carNumber: '',
            userId:'',
            carBrand:'',
            carModel:'',
            carColor:'',
            seatNum:'',
        },
        exitForm: {
            id: '',
            carNumber: '',
            entryTime: '',
            duration: '',
            fee: 0
        }
    },
    created() {
        this.loadUserInfo();
        this.loadParkingRecords();
        this.loadStats();
        this.loadAvailableSpots();
    },
    methods: {
        loadUserInfo() {
            axios.get('../../userInfo')
                .then(response => {
                    if (response.data.success) {
                        this.userInfo = response.data.data;
                    }
                })
                .catch(error => {
                    console.error('Error loading user info:', error);
                });
        },

        // 加载停车记录
        loadParkingRecords() {
            axios.get('/Parks/tempParking/list')
                .then(response => {
                    if (response.data.code === 0) {
                        this.parkingRecords = response.data.data;
                        console.log(response.data.data);
                        console.log(this.parkingRecords);
                        console.log("加载停车记录成功");
                    } else {
                        alert(response.data.msg || '加载停车记录失败');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('加载停车记录失败');
                });
        },

        // 加载统计数据
        loadStats() {
            axios.get('/Parks/tempParking/stats')
                .then(response => {
                    if (response.data.code === 0) {
                        this.stats = response.data.data;
                        console.log("加载统计数据成功",this.stats);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                });
        },

        // 加载可用车位
        loadAvailableSpots() {
            axios.get('/Parks/parkingSeat/getTempAvailableSeats')
                .then(response => {
                    if (response.data.code === 0) {
                        console.log(response.data.data + "可用车位");
                        this.availableSpots = response.data.data;
                    
                    }else{
                        alert(response.data.msg || '加载可用车位失败');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('加载可用车位失败');
                });
        },

        // 显示入场表单
        showEntryForm() {
            if (this.availableSpots.length === 0) {
                alert('当前没有可用车位');
                return;
            }
            this.entryForm = {
                userId:'',
                carBrand:'',
                carModel:'',
                carColor:'',
                carNumber: '',
                seatNum: this.availableSpots[0].seatNum
            };
            this.showEntryModal = true;
        },

        // 显示出场表单
        showExitForm(record) {
            console.log("record: " + record);
            console.log("record.carNumber: " + record.carNum);
            axios.post('/Parks/tempParking/exit',record.carNum)
                // carNumber: record.carNumber, // 出场时需要传入车牌号
                // entryTime: record.entryTime, // 出场时需要传入入场时间
                // fee: this.exitForm.fee
            
                .then(response => {
                    console.log(record.carNumber);
                    if (response.data.code === 0) {
                        alert('结算出场成功');
                        this.closeExitModal();
                        this.loadParkingRecords();
                        this.loadStats();
                        this.loadAvailableSpots();
                        // 打印小票
                        // this.printReceipt(response.data.data);
                    } else {
                        alert(response.data.msg || '结算出场失败');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('结算出场失败');
                });
        },

        // 关闭入场模态框
        closeEntryModal() {
            this.showEntryModal = false;
            this.entryForm = {
                userId:'',
                carBrand:'',
                carModel:'',
                carColor:'',
                seatNum:'',
                carNumber: '',
                
            };
        },

        // 关闭出场模态框
        closeExitModal() {
            this.showExitModal = false;
            this.exitForm = {
                id: '',
                carNumber: '',
                entryTime: '',
                duration: '',
                fee: 0
            };
        },

        // 提交入场表单
        submitEntryForm() {
            axios.post('/Parks/tempParking/entry', this.entryForm)
                .then(response => {
                    if (response.data.code === 0) {
                        alert('登记入场成功');
                        this.closeEntryModal();
                        this.loadParkingRecords();
                        this.loadStats();
                        this.loadAvailableSpots();
                    } else {
                        alert(response.data.msg || '登记入场失败');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('登记入场失败');
                });
        },

        // 确认出场结算
        confirmExit() {
        //     axios.post('/Parks/tempParking/exit', {
        //         id: this.exitForm.id,
        //         fee: this.exitForm.fee
        //     })
        //         .then(response => {
        //             if (response.data.code === 0) {
        //                 alert('结算出场成功');
        //                 this.closeExitModal();
        //                 this.loadParkingRecords();
        //                 this.loadStats();
        //                 this.loadAvailableSpots();
        //                 // 打印小票
        //                 this.printReceipt(response.data.data);
        //             } else {
        //                 alert(response.data.msg || '结算出场失败');
        //             }
        //         })
        //         .catch(error => {
        //             console.error('Error:', error);
        //             alert('结算出场失败');
        //         });
        // },
},

handleSearch() {
    if (this.searchKey) {
        const results = this.parkingRecords.filter(seat => 
            (seat.carNum && seat.carNum.includes(this.searchKey))
        );

        if( results.length === 0) {
            alert("未找到该车辆");
            return;
        }
        this.parkingRecords = results; // 更新用户列表为搜索结果
    } else {
        this.loadParkingRecords(); // 如果没有搜索关键字，重新获取所有用户
    }
},

        // 计算停车时长
        getDuration(record) {
            if (!record.entryTime) return '-';
            if (record.status === 'parking') {
                const start = new Date(record.entryTime);
                const now = new Date();
                const hours = Math.floor((now - start) / (1000 * 60 * 60));
                const minutes = Math.floor(((now - start) % (1000 * 60 * 60)) / (1000 * 60));
                return `${hours}小时${minutes}分钟`;
            }
            return record.duration || '-';
        },

        // 获取状态样式类
        getStatusClass(status) {
            return status === undefined ? 'status-parking' : 'status-completed';
        },

        // 获取状态文本
        getStatusText(status) {
            return status === undefined ? '停车中' : '已完成';
        },


        // 获取状态样式类
        // GetStatusClass(status) {
        //     return status === undefined ? 'status-parking' : '';
        // },

        // 打印小票
        printReceipt(record) {
            const printWindow = window.open('', '_blank');
            printWindow.document.write(`
                <html>
                <head>
                    <title>停车费用小票</title>
                    <style>
                        body { font-family: Arial; padding: 20px; }
                        .receipt { width: 300px; margin: 0 auto; }
                        .title { text-align: center; font-size: 18px; margin-bottom: 20px; }
                        .item { margin-bottom: 10px; }
                        .total { margin-top: 20px; font-weight: bold; }
                    </style>
                </head>
                <body>
                    <div class="receipt">
                        <div class="title">停车费用小票</div>
                        <div class="item">车牌号：${record.carNum}</div>
                        <div class="item">入场时间：${record.entryDate} ${record.entryTime}</div>
                        <div class="item">出场时间：${record.outDate} ${record.outTime}</div>
                        <div class="item">停车时长：${record.duration}</div>
                        <div class="total">费用合计：￥${record.tempMoney}</div>
                    </div>
                    <script>
                        window.print();
                        setTimeout(() => window.close(), 500);
                    </script>
                </body>
                </html>
            `);
        },

        // 退出登录
        handleLogout() {
            axios.post('/Parks/logout')
                .then(() => {
                    sessionStorage.removeItem('userInfo');
                    window.location.href = '../../login.html';
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('退出失败');
                });
        }
    }
}); 